package apis

import (
	"QImages/database"
	"QImages/entity"
	"QImages/global"
	"QImages/provider"
	"QImages/serializer"
	"QImages/utils"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// GetImages 分页获取图片
func GetImages(c *gin.Context) {
	page := c.Query("page")
	limit := c.DefaultQuery("limit", "0")
	if page == "" {
		c.JSON(http.StatusOK, serializer.ParamErr("参数不完整", nil))
		return
	}
	pageNum, err := strconv.Atoi(page)
	pageSize, err := strconv.Atoi(limit)
	results, err := entity.PageImages(pageNum, pageSize)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.Err(serializer.CodeNothingFound, "抱歉未找到相关信息", nil))
		return
	}
	var images []serializer.Image
	for _, item := range results {
		images = append(images, serializer.BuildImage(&item))
	}
	if images == nil {
		images = make([]serializer.Image, 0)
	}
	c.JSON(http.StatusOK, serializer.OK("查询成功", images))
}

// GetImageById 根据id获取图片信息
func GetImageById(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", nil))
		return
	}
	image, err := entity.FindImageById(uint(id))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.Err(serializer.CodeNothingFound, "抱歉未找到相关信息", nil))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("查找成功", serializer.BuildImage(&image)))
}

//DelImageById 根据id删除
func DelImageById(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", nil))
		return
	}
	_, err = entity.DeleteImage(uint(id))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ServerErr("删除失败", nil))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("删除成功", nil))
}

// Refresh 重新刷新图片，更新图库
func Refresh(c *gin.Context) {
	database.DB.AutoMigrate(&entity.Image{})
	provider.StoreImages()
	c.JSON(http.StatusOK, serializer.OK("数据刷新成功", nil))
}

// GetTimeline 时间线功能
func GetTimeline(c *gin.Context) {
	uid, err := strconv.Atoi(c.Query("uid"))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", err))
		return
	}
	timeline, err := entity.Timeline(uint(uid))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.DBErr("", err))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("时间线查询成功", serializer.BuildTimeline(timeline)))
}

type ParaImage struct {
	Url    string `json:"url"  binding:"required"`
	Desc   string `json:"desc"  binding:"required"`
	Title  string `json:"title"  binding:"required"`
	Label  string `json:"label"  binding:"required"`
	UserID uint   `json:"userId"  binding:"required"`
}

// PostImage 上传图片
func PostImage(c *gin.Context) {
	var param ParaImage
	err := c.ShouldBindJSON(&param)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", err))
		return
	}
	image := entity.Image{
		Url:    param.Url,
		Title:  param.Title,
		Desc:   param.Desc,
		Label:  param.Label,
		UserID: param.UserID,
	}
	id, err := image.Insert()
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.DBErr("图片上传失败", err))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("图片保存成功", id))
}

// UploadImage 上传图片api
func UploadImage(c *gin.Context) {
	header, err := c.FormFile("image")
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", nil))
		return
	}
	path := global.Config.PhotoPath
	if !utils.IsExist(path) {
		err := os.MkdirAll(path, os.ModePerm)
		if err != nil {
			log.Println(err)
		}
	}
	suffixs := strings.Split(header.Filename, ".")
	name := strings.ReplaceAll(uuid.New().String(), "-", "") + "." + suffixs[len(suffixs)-1]
	if err := c.SaveUploadedFile(header, path+name); err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ServerErr("图片上传失败", err))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("图片"+header.Filename+"上传成功", name))
}

//UpdateImage 更新图片
func UpdateImage(c *gin.Context) {
	var param ParaImage
	if err := c.ShouldBind(&param); err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr(err.Error(), nil))
		return
	}
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", nil))
		return
	}
	image := entity.Image{
		Url:    param.Url,
		Desc:   param.Desc,
		Title:  param.Title,
		Label:  param.Label,
		UserID: param.UserID,
	}
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("id存在错误", nil))
		return
	}
	res, err := image.Update(uint(id))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.DBErr("出现错误", nil))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("更新成功", serializer.BuildImage(&res)))
}
